package com.egg.ylt.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.egg.ylt.R;
import com.egg.ylt.Utils.API;
import com.egg.ylt.Utils.Constants;
import com.egg.ylt.Utils.CustomUtils;
import com.egg.ylt.Utils.StatusBarUtil;
import com.egg.ylt.Utils.StringUtil;
import com.egg.ylt.adapter.ADA_OtherServiceAdapter;
import com.egg.ylt.adapter.ADA_StoreListAdapter;
import com.egg.ylt.pojo.ShopServerByIdEntity;
import com.egg.ylt.presenter.impl.ShopServerPresenterImpl;
import com.egg.ylt.view.IShopServerView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMWeb;
import com.yonyou.framework.library.base.BaseActivity;
import com.yonyou.framework.library.bean.ErrorBean;
import com.yonyou.framework.library.common.utils.ToastUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.loader.ImageLoader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ACT_ServiceItem extends BaseActivity<ShopServerPresenterImpl> implements IShopServerView {


    @BindView(R.id.title_rl)
    RelativeLayout mTitleRl;

    @BindView(R.id.collect_iv)
    ImageView mCollectIv;

    @BindView(R.id.banner)
    Banner mBanner;

    @BindView(R.id.name_tv)
    TextView mNameTv;

    @BindView(R.id.description_tv)
    TextView mDescriptionTv;

    @BindView(R.id.price_tv)
    TextView mPriceTv;

    @BindView(R.id.old_price_tv)
    TextView mOldPriceTv;

    @BindView(R.id.reserved_count_tv)
    TextView mReservedCountTv;

    @BindView(R.id.store_list_rlv)
    RecyclerView mStoreListRlv;

    @BindView(R.id.service_content_tv)
    TextView mServiceContentTv;

    @BindView(R.id.attention_tv)
    TextView mAttentionTv;

    @BindView(R.id.other_service_rlv)
    RecyclerView mOtherServiceRlv;

    private String mShopId;

    private String mStorePhone;


    private com.yonyou.framework.library.dialog.AlertDialog mShareDialog;

    private ADA_StoreListAdapter mStoreListAdapter;

    private ADA_OtherServiceAdapter mOtherServiceAdapter;

    private boolean mIsCollected = false;
    private String mServiceImageUrl;
    private String mServiceId;
    private String mServiceIntro;

    @Override
    protected void getBundleExtras(Bundle extras) {

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_service_item;
    }

    @Override
    protected View getLoadingTargetView() {
        return null;
    }

    @Override
    protected void initViewsAndEvents() {
        //设置沉浸式状态栏
        StatusBarUtil.setStatusBarColor(this, R.color.ylt_whit);
        StatusBarUtil.StatusBarLightMode(this);
        CustomUtils.setImmersiveStatusBar(mContext, mTitleRl);


        String id = getIntent().getStringExtra("id");
        mShopId = getIntent().getStringExtra("shopId");
        mServiceImageUrl = getIntent().getStringExtra("serviceImageUrl");
        mStorePhone = getIntent().getStringExtra("storePhone");


        //请求服务详情
        mPresenter.getService(Constants.TOKEN, id, mShopId);
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    @Override
    protected boolean isApplyKitKatTranslucency() {
        return false;
    }

    @Override
    public void showBusinessError(ErrorBean error) {

    }

    @Override
    public void getServiceData(ShopServerByIdEntity entity) {
        if (entity == null) {
            return;
        }

        mServiceId = entity.getId();
        mServiceIntro = (StringUtil.isEmpty(entity.getFitAge()) ? "" : (
                entity.getFitAge() + "岁")) + (StringUtil.isEmpty(entity.getServiceTime()) ? "" :
                (" | " + (entity.getServiceTime() + "分钟"))) + (StringUtil.isEmpty(entity.getServiceType()) ? "" :
                (" | " + entity.getServiceType()));

        //Banner
        List<ShopServerByIdEntity.BannerListEntity> bannerEntities = entity.getBannerList();
        if (bannerEntities != null && !bannerEntities.isEmpty()) {
            List<String> imageUrls = new ArrayList<>();
            final List<String> titles = new ArrayList<>();
            for (int i = 0; i < bannerEntities.size(); i++) {
                titles.add("");
                imageUrls.add(bannerEntities.get(i).getImageUrl());
            }
            //设置banner样式
            mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
            //设置图片加载器
            mBanner.setImageLoader(new ImageLoader() {
                @Override
                public void displayImage(Context context, Object path, ImageView imageView) {
                    if (context != null) {
                        //Glide 加载图片简单用法
                        Glide.with(context).load(path).error(R.mipmap.ic_banner_default).placeholder(R.mipmap.ic_banner_default).dontAnimate().into(imageView);
                    }
                }
            });
            //设置图片集合
            mBanner.setImages(imageUrls);
            //设置banner动画效果
            mBanner.setBannerAnimation(Transformer.DepthPage);
            //设置标题集合（当banner样式有显示title时）
            mBanner.setBannerTitles(titles);
            //设置自动轮播，默认为true
            mBanner.isAutoPlay(true);
            //设置轮播时间
            mBanner.setDelayTime(3000);
            //设置指示器位置（当banner模式中有指示器时）
            mBanner.setIndicatorGravity(BannerConfig.CENTER);

        }
        //banner设置方法全部调用完毕时最后调用
        mBanner.start();

        mNameTv.setText(entity.getName());

        mDescriptionTv.setText(entity.getServiceIntro());

        mPriceTv.setText(StringUtil.getBigDecimalPrice(entity.getMemberPrice()));

        mOldPriceTv.setText("¥" + StringUtil.getBigDecimalPrice(entity.getPrice()));
        CustomUtils.setMiddleLine(mOldPriceTv);

        mReservedCountTv.setText("已预约" + entity.getNum());

        mStoreListRlv.setNestedScrollingEnabled(false);
        mStoreListRlv.setLayoutManager(new LinearLayoutManager(this));
        if (mStoreListAdapter == null) {
            mStoreListAdapter = new ADA_StoreListAdapter(entity.getShopList());
            mStoreListRlv.setAdapter(mStoreListAdapter);
        } else {
            mStoreListAdapter.notifyDataSetChanged();
        }

        mServiceContentTv.setText(entity.getServiceDetail());

//        mAttentionTv.setText(entity.getStress());
        // 解析 html
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mAttentionTv.setText(Html.fromHtml(entity.getStress(), Html.FROM_HTML_MODE_COMPACT));
        } else {
            mAttentionTv.setText(Html.fromHtml(entity.getStress()));
        }

        mOtherServiceRlv.setNestedScrollingEnabled(false);
        mOtherServiceRlv.setLayoutManager(new LinearLayoutManager(this));
        if (mOtherServiceAdapter == null) {
            mOtherServiceAdapter = new ADA_OtherServiceAdapter(entity.getServiceList(), mShopId, mStorePhone);
            mOtherServiceRlv.setAdapter(mOtherServiceAdapter);
            mOtherServiceAdapter.notifyDataSetChanged();
        } else {
            mOtherServiceAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void cancelCollect() {
        mIsCollected = false;
        changeCollected();
    }

    @Override
    public void doCollect() {
        mIsCollected = true;
        changeCollected();
    }

    private void changeCollected() {
        mCollectIv.setSelected(mIsCollected);
    }

    @OnClick(value = {R.id.back_iv, R.id.share_iv, R.id.collect_iv, R.id.see_detail_rl, R.id.phone_tv,
            R.id.order_now_tv})
    public void toggleEvent(View view) {
        switch (view.getId()) {
            case R.id.back_iv:
                finish();
                break;
            case R.id.share_iv:
                umShareDialogShow();
                break;
            case R.id.collect_iv:
                if (StringUtil.isEmpty(Constants.TOKEN)) {
                    readyGo(ACT_UserLogin.class);
                    return;
                }
                if (mIsCollected) {
                    mPresenter.setCancelMessage(Constants.TOKEN, mShopId);
                } else {
                    mPresenter.setCollectMessage(Constants.TOKEN, mShopId, Constants.COMPANYID);
                }
                break;
            case R.id.see_detail_rl:
                Bundle b = new Bundle();
                b.putSerializable("title", "服务项目详情");
                b.putSerializable("url",
                        API.SERVICE_DETAIL_SHARE_URL + "?token=" + Constants.TOKEN + "&id=" + mServiceId + "&shopId=" + mShopId +
                                "&isShare=false#/serviceInfo");
                readyGo(ACT_WebView.class, b);
                break;
            case R.id.order_now_tv:
                //跳转到预约界面
                Bundle bundle = new Bundle();
                bundle.putString("shopId", mShopId);
                bundle.putString("serviceId", mServiceId);
                bundle.putString("servicePrice", mPriceTv.getText().toString());
                bundle.putString("serviceName", mNameTv.getText().toString());
                bundle.putString("serviceIntro", mServiceIntro);
                bundle.putString("serviceImageUrl", mServiceImageUrl);
                bundle.putString("storePhone", mStorePhone);
                readyGo(ACT_ShopAppointment.class, bundle);
                break;
            case R.id.phone_tv:
                CustomUtils.setCallPhoneDialog(this, mStorePhone);
                break;
        }
    }

    /**
     * 分享的dialog展示
     */
    public void umShareDialogShow() {
        //判断不为空直接关闭
        if (mShareDialog != null) {
            mShareDialog.dismiss();
        }
        //友盟分享链接的对象
        String uri =
                API.SERVICE_DETAIL_SHARE_URL + "?token=" + Constants.TOKEN + "&id=" + mServiceId + "&shopId=" + mShopId +
                        "&isShare=false#/serviceInfo";
        final UMWeb web = new UMWeb(uri);
        web.setTitle(" ");
        web.setDescription(" ");
        mShareDialog = new com.yonyou.framework.library.dialog.AlertDialog.Builder(mContext)
                .setContentView(R.layout.dialog_um_share_view)
                .setCancelableOntheOutside(true)
                .setWidthAndHeight(mScreenWidth, 900)
                .fromBottom(true)
                .create();
        //设置点击事件
        //微信好友
        mShareDialog.setOnClickListener(R.id.btn_share_wx, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isInstallByread("com.tencent.mm")) {
                    new ShareAction(mContext)
                            .setPlatform(SHARE_MEDIA.WEIXIN)//传入平台
                            .withMedia(web)//分享链接
                            .setCallback(shareListener)//回调监听器
                            .share();
                } else {
                    ToastUtil.makeText(mContext, "微信未安装", false);
                }
            }
        });
        //QQ空间
        mShareDialog.setOnClickListener(R.id.btn_share_qq_space, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (isInstallByread("com.tencent.mobileqq")) {
                    new ShareAction(mContext)
                            .setPlatform(SHARE_MEDIA.QZONE)//传入平台
                            .withMedia(web)//分享链接
                            .setCallback(shareListener)//回调监听器
                            .share();
                } else {
                    ToastUtil.makeText(mContext, "QQ应用未安装", false);
                }
            }
        });
        //新浪微博
        mShareDialog.setOnClickListener(R.id.btn_share_sina, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ShareAction(mContext)
                        .setPlatform(SHARE_MEDIA.SINA)//传入平台
                        .withMedia(web)//分享链接
                        .setCallback(shareListener)//回调监听器
                        .share();
            }
        });
        //QQ好友
        mShareDialog.setOnClickListener(R.id.btn_share_qq_friend, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isInstallByread("com.tencent.mobileqq")) {
                    new ShareAction(mContext)
                            .setPlatform(SHARE_MEDIA.QQ)//传入平台
                            .withMedia(web)//分享链接
                            .setCallback(shareListener)//回调监听器
                            .share();
                } else {
                    ToastUtil.makeText(mContext, "QQ应用未安装", false);
                }
            }
        });
        //微信朋友圈
        mShareDialog.setOnClickListener(R.id.btn_share_circle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isInstallByread("com.tencent.mm")) {
                    new ShareAction(mContext)
                            .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)//传入平台
                            .withMedia(web)//分享链接
                            .setCallback(shareListener)//回调监听器
                            .share();
                } else {
                    ToastUtil.makeText(mContext, "微信未安装", false);
                }
            }
        });
        //取消dialog
        mShareDialog.setOnClickListener(R.id.btn_share_cancel, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mShareDialog != null) {
                    mShareDialog.dismiss();
                }
            }
        });
        //展示
        mShareDialog.show();

    }

    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(mContext, "分享成功", Toast.LENGTH_LONG).show();
            //判断不为空直接关闭
            if (mShareDialog != null) {
                mShareDialog.dismiss();
            }
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(mContext, "分享失败" + t.getMessage(), Toast.LENGTH_LONG).show();
            //判断不为空直接关闭
            if (mShareDialog != null) {
                mShareDialog.dismiss();
            }
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            if (platform.getName().equals("QQ")) {

            } else {
                Toast.makeText(mContext, "取消分享", Toast.LENGTH_LONG).show();
            }
            //判断不为空直接关闭
            if (mShareDialog != null) {
                mShareDialog.dismiss();
            }

        }
    };

    /**
     * 判断是否安装目标应用
     *
     * @param packageName 目标应用安装后的包名
     * @return 是否已安装目标应用
     */
    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }
}
